package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.mapper.*;
import cn.net.shuxing.yifu.mysiteforme.admin.base.MySysUser;
import cn.net.shuxing.yifu.mysiteforme.admin.entity.User;
import cn.net.shuxing.yifu.mysiteforme.admin.service.UserService;
import cn.net.shuxing.yifu.mysiteforme.admin.util.ToolUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserService{


    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    UserBankCardMapper userBankCardMapper;

    @Autowired
    private SysUserRealInfoService userRealInfoService;

    @Autowired
    private UserBankCardService userBankCardService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CityAgentCommissionService cityAgentCommissionService;

    @Autowired
    private UserRelationshipService userRelationshipService;

    @Autowired
    private BaseAreaService baseAreaService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private CardTypeMapper cardTypeMapper;

    @Autowired
    protected UserService userService;

    /**
     * 获取后台用户列表
     * @return
     */
    public List<SysUser> selectSysUserList(Integer type,Integer startPageNo, Integer pageSize,
                                           String nickName,String tel,String idCardNum,
                                           String startTime,String endTime){
        List<SysUser> sysUserList = sysUserMapper.selectSysUserListByType(type,startPageNo,pageSize,
                nickName,tel,idCardNum,startTime,endTime,null,null,null);
        if(null != sysUserList && sysUserList.size() > 0){
            for (SysUser sysUser:sysUserList) {
                UserBankCard userBankCard = userBankCardMapper.selectUserBankCard(2,Integer.valueOf(sysUser.getId().toString()));
                if(null != userBankCard){
                    sysUser.setHolderName(userBankCard.getHolderName());
                    sysUser.setOpenBank(userBankCard.getOpenBank());
                    sysUser.setOpenBankBranch(userBankCard.getOpenBankBranch());
                    sysUser.setBankCardNum(userBankCard.getBankCardNum());
                    sysUser.setIdCardNum(userBankCard.getIdCardNum());
                }
                if(null != sysUser.getCardTypeId()){
                    CardType cardType1 = cardTypeMapper.selectById(sysUser.getCardTypeId());
                    if(null != cardType1){
                        sysUser.setCardTypeName(cardType1.getName());
                    }
                }
            }
        }
        return sysUserList;
    }

    /**
     * 新增兼职股东
     * @param idCardNum
     * @param nickName
     * @param cardTypeId
     * @param tel
     * @param openBank
     * @param openBankBranch
     * @param bankCardNum
     * @param password
     * @return
     */
    public BaseDto add(String idCardNum,String nickName,Integer cardTypeId,
                       String tel, String openBank,String openBankBranch,
                       String bankCardNum,String password){

        BaseDto baseDto = new BaseDto();
        List<SysUserRealInfo> failRegistryUserRealInfoList = new ArrayList<>();
        /** 身份实名认证 **/
        SysUserRealInfo sysUserRealInfo = new SysUserRealInfo();
        sysUserRealInfo.setCardTypeId(cardTypeId);
        sysUserRealInfo.setIdCardNum(idCardNum);
        sysUserRealInfo.setRealName(nickName);
        if (!userRealInfoService.verify(idCardNum,nickName))
        {
            baseDto.setCode(CodeConst.ERROR);
            failRegistryUserRealInfoList.add(sysUserRealInfo);
        }

        /** 银行卡实名认证 **/
        UserBankCard userBankCard = new UserBankCard();
        userBankCard.setBankCardNum(bankCardNum);
        userBankCard.setHolderName(nickName);
        userBankCard.setOpenBank(openBank);
        userBankCard.setOpenBankBranch(openBankBranch);
        userBankCard.setPhoneNum(tel);
        userBankCard.setIdCardNum(idCardNum);
        if (!userBankCardService.verify(userBankCard))
        {
            baseDto.setCode(CodeConst.ERROR);
            failRegistryUserRealInfoList.add(sysUserRealInfo);
        }

        SysUser sysUser2 = new SysUser();
        sysUser2.setNickName(nickName);
        sysUser2.setTel(tel);
        sysUser2.setLoginName(tel);
        sysUser2.setType(4);
        sysUser2.setCreateDate( LocalDateTime.now());
        sysUser2.setDelFlag("0");
        sysUser2.setPassword(password);
        SysUser sysUser = getPassword(sysUser2);
        sysUserMapper.insertSelective(sysUser);
        SysUser sysUser1 = sysUserMapper.selectByTel(tel);
        if(sysUser1 != null) {
            /** 获取userId **/
            Long userIdStr = sysUser1.getId();
            Integer userId = Integer.valueOf(userIdStr.toString());
            //进行用户角色绑定
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userIdStr.toString());
            sysUserRole.setRoleId("3");
            sysUserRoleMapper.insertSelective(sysUserRole);
//        /** 完善用户信息，构建UserInfo对象并存入user_info表 **/
//        UserInfo userInfo = new UserInfo();
//        userInfo.setId(userId);
//        /** 默认股东昵称就是真实姓名 **/
//        userInfo.setNickName(nickName);
//        userInfoService.insert(userInfo);

            /** 股东实名制，构建股东用户真实信息对象UserRealInfo对象，并存入user_real_info表 **/
            sysUserRealInfo.setId(userIdStr);
            userRealInfoService.insert(sysUserRealInfo);

            /** 给股东绑定银行卡，构建UserBankCard对象，并存入user_bank_card表中 **/
            userBankCard.setUserId(userId);
            userBankCard.setType(2);
            userBankCardService.insert(userBankCard);

            //初始化佣金比例表
            CityAgentCommission cityAgentCommission = new CityAgentCommission();
            cityAgentCommission.setUserId(userIdStr);
            cityAgentCommission.setCommRate(new BigDecimal(0));
            cityAgentCommission.setCumulativeComm(new BigDecimal(0));
            cityAgentCommission.setUnsettledComm(new BigDecimal(0));
            cityAgentCommissionService.insert(cityAgentCommission);

            if (baseDto.getCode() == CodeConst.ERROR) {
                return baseDto;
            }
            baseDto.setData("全部注册成功");
        }
        return baseDto;
    }

    public BaseDto update(Integer userId,String nickName,String tel){
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId.toString()));
        sysUser.setNickName(nickName);
        sysUser.setTel(tel);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        BaseDto baseDto = new BaseDto();
        baseDto.setCode(CodeConst.OK);
        baseDto.setData("修改成功");
        return baseDto;
    }

    public BaseDto freeze(Integer type,Integer userId){
        BaseDto baseDto = new BaseDto();
        if(null != userId){
            User user = userService.findUserById(Long.valueOf(userId));
            user.setId(Long.valueOf(userId));
            //冻结
            if(type == 1){
                user.setLocked(true);
                userService.updateUser(user);
                baseDto.setData("冻结成功");
            }
            //解冻
            if(type == 2){
                user.setLocked(false);
                userService.updateUser(user);
                baseDto.setData("解冻成功");
            }
        }
        return baseDto;
    }


    public BaseDto detail(Long id){
        BaseDto baseDto = new BaseDto();
        List<SysUser> list = new ArrayList<>();
        SysUser user = sysUserMapper.detail(id);
        list.add(user);
        baseDto.setData(list);
        return baseDto;
    }

    public BaseDto saveSysUser(Integer userId,String nickName,String tel){
        BaseDto baseDto = new BaseDto();
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId.toString()));
        sysUser.setNickName(nickName);
        sysUser.setTel(tel);
        int m = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if(m > 0){
            baseDto.setData("修改成功");
        }else {
            baseDto.setData("修改失败");
        }
        return baseDto;
    }

    public BaseDto selectById(Long userId){
        BaseDto baseDto = new BaseDto();
        baseDto.setData(sysUserMapper.detail(userId));
        return baseDto;
    }


    public BaseDto updateAgent(Integer userId,String nickName,String tel,Integer province,Integer city,
                               Integer district,Double commRate){
        BaseDto baseDto = new BaseDto();
        //修改基础信息
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId.toString()));
        sysUser.setNickName(nickName);
        sysUser.setTel(tel);
        sysUser.setLoginName(tel);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        baseDto.setData("修改成功");
        return baseDto;
    }

    public BaseDto addAgent(Long userId,String nickName,String tel,Integer province,Integer city,
                               Integer district,String password,Double commRate){
        BaseDto baseDto = new BaseDto();

        //修改基础信息
        SysUser sysUser1 = new SysUser();
        sysUser1.setLoginName(tel);
        sysUser1.setNickName(nickName);
        sysUser1.setTel(tel);
        sysUser1.setType(2);
        sysUser1.setPassword(password);
        SysUser sysUser = getPassword(sysUser1);
        sysUserMapper.insertSelective(sysUser);
        SysUser user = sysUserMapper.selectByTel(tel);
        if(null != user) {
            //进行用户角色绑定
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(user.getId().toString());
            sysUserRole.setRoleId("4");
            sysUserRoleMapper.insertSelective(sysUserRole);
            //修改佣金信息
            CityAgentCommission cityAgentCommission = new CityAgentCommission();
            cityAgentCommission.setUserId(user.getId());
            cityAgentCommission.setProvince(province);
            cityAgentCommission.setCity(city);
            cityAgentCommission.setDistrict(district);
            cityAgentCommission.setCommRate(BigDecimal.valueOf(commRate));
            cityAgentCommissionService.insert(cityAgentCommission);
            //绑定关系
            UserRelationship userRelationship = new UserRelationship();
            userRelationship.setType(1);
            userRelationship.setUserId1(userId);
            userRelationship.setUserId2(user.getId());
            userRelationshipService.add(userRelationship);
            baseDto.setData("新增成功");
        }
        return baseDto;
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    public BaseDto resetPassword(Long userId){
        BaseDto baseDto = new BaseDto();
        User user = userService.findUserById(Long.valueOf(userId));
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId.toString()));
        sysUser.setPassword("111111");
        SysUser sysUser1 = getPassword(sysUser);
        user.setSalt(sysUser1.getSalt());
        user.setPassword(sysUser1.getPassword());
        userService.updateUser(user);
        baseDto.setData("重置密码成功");
        return baseDto;
    }

    /**
     * 获取城市代理商下属订单列表
     * @return
     */
    public BaseDto agentOrderList(Integer startPageNo, Integer pageSize,Long userId){
        BaseDto baseDto = new BaseDto();
        //获取该代理商的下属业务员列表
        List<UserRelationship> userRelationshipList = userRelationshipService.selectList(1,userId);
        if(null != userRelationshipList && userRelationshipList.size() > 0){
            String salesmanIds = "";
            for (UserRelationship userRelation :userRelationshipList) {
                if(null != userRelation && null != userRelation.getUserId2()){
                    salesmanIds = salesmanIds + userRelation.getUserId2() + ",";
                }
            }
            if(!salesmanIds.equals("")) {
                salesmanIds = salesmanIds.substring(0, salesmanIds.length() - 1);
                //获取下属店铺
                List<UserRelationship> urList = userRelationshipService.selectListByUserIdStr(2,salesmanIds);
                String userIdStr = "";
                if(null != urList && urList.size() > 0){
                    for (UserRelationship ur:urList) {
                        if(null != ur && ur.getUserId2() != null){
                            userIdStr = userIdStr + ur.getUserId2() + ",";
                        }
                    }
                    if(!userIdStr.equals("")){
                        //获取订单列表
                        //todo




                    }else{
                        baseDto.setData("暂无订单数据!");
                    }
                }else{
                    baseDto.setData("暂无订单数据!");
                }
            }else{
                baseDto.setData("暂无订单数据!");
            }
        }else{
            baseDto.setData("暂无订单数据!");
        }
        return baseDto;
    }

    /**
     * 获取城市代理商下属业务员列表
     */
    public BaseDto salemanList(Integer startPageNo, Integer pageSize,Long userId){
        BaseDto baseDto = new BaseDto();
        //获取该代理商的下属业务员列表
        List<UserRelationship> userRelationshipList = userRelationshipService.selectPageList(startPageNo,pageSize,1,userId);
        if(null != userRelationshipList && userRelationshipList.size() > 0) {
            //获取业务员基本信息
            List<SysUser> sysUserList = new ArrayList<>();
            for (UserRelationship ur:userRelationshipList) {
                if(null != ur && null != ur.getUserId2()){
                     SysUser sysUser = sysUserMapper.selectById(ur.getUserId2());
                     sysUserList.add(sysUser);
                }
            }
            baseDto.setData(sysUserList);
        }else{
            baseDto.setData("暂无业务员数据!");
        }
        return baseDto;
    }

    /**
     * 获取当前业务员下属店铺的订单数据
     * @param startPageOn
     * @param pageSize
     * @param userId
     * @return
     */
    public BaseDto shopOrder(Integer startPageOn,Integer pageSize,Long userId){
        BaseDto baseDto = new BaseDto();
        //获取下属店铺列表
        List<UserRelationship> userRelationshipList = userRelationshipService.selectList(2,userId);
        if(null != userRelationshipList && userRelationshipList.size() > 0){
            //获取店铺列表
            String userIdStr = "";
            for (UserRelationship ur:userRelationshipList) {
                if(null != ur && null != ur.getUserId2()){
                    userIdStr = userIdStr + ur.getUserId2() + ",";
                }
            }
            if(!userIdStr.equals("")){
                userIdStr = userIdStr.substring(0,userIdStr.length() - 1);
            }
            //获取店铺订单列表（分页）

        }
        return baseDto;
    }

    /**
     * 新增业务员
     */
    public BaseDto addSaleman(String nickName, String tel, BigDecimal commRate,String password,Long userId){
        BaseDto baseDto = new BaseDto();
        SysUser suser = sysUserMapper.detail(userId);
        if(null != suser && suser.getCommRate().compareTo(BigDecimal.ZERO)>0){
            if(suser.getCommRate().compareTo(commRate)<0){
                baseDto.setData("佣金比例不得超过"+suser.getCommRate());
                return baseDto;
            }
        }
        //添加基础信息
        SysUser sysUser2 = new SysUser();
        sysUser2.setLoginName(tel);
        sysUser2.setNickName(nickName);
        sysUser2.setTel(tel);
        sysUser2.setType(3);//业务员
        sysUser2.setCreateDate( LocalDateTime.now());
        sysUser2.setPassword(password);
        SysUser sysUser = getPassword(sysUser2);
        sysUserMapper.insertSelective(sysUser);
        /** 获取 salemanId **/
        SysUser saleman = sysUserMapper.selectByTel(tel);
        Long salemanId = saleman.getId();
        //添加佣金比例信息
        CityAgentCommission cityAgentCommission = new CityAgentCommission();
        cityAgentCommission.setCommRate(commRate);
        cityAgentCommission.setUserId(salemanId);
        cityAgentCommissionService.add(cityAgentCommission);
        //添加城市代理商与业务员的关系
        UserRelationship userRelationship = new UserRelationship();
        userRelationship.setType(1);
        userRelationship.setUserId1(userId);
        userRelationship.setUserId2(salemanId);
        userRelationshipService.add(userRelationship);
        baseDto.setData("添加成功!");
        return baseDto;
    }

    /**
     * 获取后台用户列表
     * @return
     */
    public List<SysUser> selectCityAgentList(Integer type,Integer startPageNo, Integer pageSize,
                                             Integer province,Integer city,Integer district){
        List<SysUser> sysUserList = sysUserMapper.selectSysUserListByType(type,startPageNo,pageSize,
                null,null,null,null,null,province,city,district);
        if(null != sysUserList && sysUserList.size() > 0){
            for (SysUser user:sysUserList) {
                String address = "";
                if(user.getProvince() != null){
                    BaseArea baseArea = baseAreaService.selectAreaById(user.getProvince());
                    if(null != baseArea){
                        address = baseArea.getAreaName()+" ";
                    }
                }
                if(user.getCity() != null){
                    BaseArea baseArea = baseAreaService.selectAreaById(user.getCity());
                    if(null != baseArea){
                        address = address + baseArea.getAreaName()+" ";
                    }
                }
                if(user.getDistrict() != null){
                    BaseArea baseArea = baseAreaService.selectAreaById(user.getDistrict());
                    if(null != baseArea){
                        address = address + baseArea.getAreaName();
                    }
                }
                user.setAddress(address);
            }
        }
        return sysUserList;
    }

    public BaseDto cityAgentDetail(Long userId){
        BaseDto baseDto = new BaseDto();
        List<SysUser> list = new ArrayList<>();
        SysUser user = sysUserMapper.detail(userId);
        //拼装省市区
        String address = "";
        if(null != user){
            if(user.getProvince() != null) {
                BaseArea area1 = baseAreaService.selectAreaById(user.getProvince());
                address = address + area1.getAreaName() + " ";
            }
            if(user.getCity() != null) {
                BaseArea area2 = baseAreaService.selectAreaById(user.getCity());
                address = address + area2.getAreaName() + " ";
            }
            if(user.getDistrict() != null) {
                BaseArea area3 = baseAreaService.selectAreaById(user.getDistrict());
                address = address + area3.getAreaName();
            }
        }
        user.setAddress(address);
        list.add(user);
        baseDto.setData(list);
        return baseDto;
    }

    public BaseDto getAgentDetail(Long userId){
        BaseDto baseDto = new BaseDto();
        SysUser user = sysUserMapper.detail(userId);
        baseDto.setData(user);
        return baseDto;
    }

    /**
     * 编辑业务员
     * @param nickName
     * @param tel
     * @param commRate
     * @return
     */
    public BaseDto updateSaleman(Long userId,String nickName,String tel,Double commRate){
        BaseDto baseDto = new BaseDto();
        SysUser suser = sysUserMapper.detail(userId);
        if(null != suser && suser.getCommRate().compareTo(BigDecimal.ZERO)>0){
            if(suser.getCommRate().compareTo(BigDecimal.valueOf(commRate))<0){
                baseDto.setData("佣金比例不得超过"+suser.getCommRate());
                return baseDto;
            }
        }
        //修改基础信息
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setNickName(nickName);
        sysUser.setTel(tel);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        //修改佣金比例信息
        cityAgentCommissionService.updateByUserId(userId,null,null,null,BigDecimal.valueOf(commRate));
        baseDto.setData("修改成功");
        return baseDto;
    }

    /**
     *
     */
    public SysUser getPassword(SysUser sysUser){
        ToolUtil.entryptPassword(sysUser);
        sysUser.setLocked(false);
        return sysUser;
    }
}
